<?php
// 设置响应头允许跨域请求
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// 指定上传文件的目录
$uploadDir = './files/';

// 检查文件上传是否存在错误
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $file = $_FILES['file'];

    // 检查上传过程中是否发生错误
    if ($file['error'] === UPLOAD_ERR_OK) {
        // 获取文件信息
        $fileName = basename($file['name']);
        $fileTmpPath = $file['tmp_name'];
        $fileType = $file['type'];

        // 确保目标目录存在，不存在则创建
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        // 生成唯一文件名，防止重名文件覆盖
        $uniqueFileName = uniqid() . '-' . $fileName;
        $destination = $uploadDir . $uniqueFileName;

        // 移动文件到目标目录
        if (move_uploaded_file($fileTmpPath, $destination)) {
            // 获取文件访问链接
            $fileUrl = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/' . $destination;
            
            // 返回成功响应，包含文件链接
            echo json_encode([
                'status' => 'success',
                'file_url' => $fileUrl
            ]);
        } else {
            // 返回错误响应
            http_response_code(500);
            echo json_encode([
                'status' => 'error',
                'message' => 'Failed to move uploaded file.'
            ]);
        }
    } else {
        // 返回错误响应
        http_response_code(400);
        echo json_encode([
            'status' => 'error',
            'message' => 'File upload error: ' . $file['error']
        ]);
    }
} else {
    // 返回错误响应
    http_response_code(400);
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid request or no file uploaded.'
    ]);
}
